import axios from 'axios'
import {appConfig} from '@/config/app'
import {session} from './session'

class Http {
    constructor(baseUrl) {
        this.baseUrl = baseUrl
        this.queue = {}
    }

    getInsideConfig() {
        const config = {
            baseURL: this.baseUrl,
            method: 'post'
        }
        return config
    }

    destroy(url) {
        delete this.queue[url]
    }

    interceptors(instance, url) {
        instance.interceptors.request.use(config => {
            if (this.loading) {
                this.loading.close()
                this.loading = null
            }
            if (session.get()) {
                config.headers[appConfig.tokenKey] = session.get()
            }
            this.queue[url] = true
            return config
        }, error => {
            return Promise.reject(error)
        })
        instance.interceptors.response.use(res => {
            if (res.headers[appConfig.token]) {
                session.set(res.headers[appConfig.token])
            }
            this.destroy(url)
            const {data} = res
            return data
        }, error => {
            this.destroy(url)
            return Promise.reject(error)
        })
    }

    request(options) {
        const instance = axios.create()
        options = Object.assign(this.getInsideConfig(), options)
        this.interceptors(instance, options.url)
        return instance(options)
    }
}

const baseUrl = process.env.NODE_ENV === 'development' ? appConfig.baseUrl.dev : appConfig.baseUrl.prod

export const http = new Http(baseUrl)
